#include "UserProfileManager.h"

UserProfileManager* UserProfileManager::instance = NULL;

UserProfileManager::UserProfileManager() {
	daoFactory = DAOFactory::getDAOFactory();
}

UserProfileManager* UserProfileManager::getInstance() {
	if (instance == NULL)
		instance = new UserProfileManager();

	return instance;
}

UserProfileManager::~UserProfileManager() {
	delete daoFactory;
}

void UserProfileManager::updateUserProfile(const std::string& device_code,
		int content_id, int rating) {
	try {
		daoFactory->connect_db();
	} catch (std::exception &ex) {
		Log::error(ex.what());
		return;
	}

	Preference preference;
	Content content;
	User user;

	try {
		content = daoFactory->getContentDAO()->loadContentById(content_id);
		if (content.getId() == NOT_FOUND) {
			//Event Information Table (EIT)
			//TODO
			std::string content_name = "À Prova de Tudo - Discovery Channel";
			std::string genre_name = "Documentário";

			Genre genre =
					daoFactory->getGenreDAO()->loadGenreByName(genre_name);

			content.setName(content_name);
			content.setGenre(genre);
			content.setBegin(1);
			content.setDuration(1);
			daoFactory->getContentDAO()->save(content);
			content = daoFactory->getContentDAO()->loadContentByName(
					content_name);
			Log::verbose(std::string("New content identified: ")
					+ content.getName() + std::string("with genre: ")
					+ genre.getName());
		} else {
			Log::log_oss << "Content '" << content.getName() << "' found";
			Log::verbose();
		}

		user = daoFactory->getUserDAO()->loadUserByDeviceCode(device_code);
		if (user.getId() == NOT_FOUND) {
			Log::verbose("New user identified");
			user.setDeviceCode(device_code);
			daoFactory->getUserDAO()->save(user);
			user = daoFactory->getUserDAO()->loadUserByDeviceCode(device_code);
		} else {
			Log::log_oss << "User " << user.getId() << " found with device "
					<< user.getDeviceCode();
			Log::verbose();
		}

		preference.setContent(content);
		preference.setUser(user);
		preference.setRating(rating);
		preference.setDate(0);
		daoFactory->getPreferenceDAO()->save(preference);
		Log::verbose("New preference added to the user profile");
	} catch (std::exception &ex) {
		Log::error(ex.what());
		return;
	}
}

